/**
 * 对话框
 */
function scDialog(){
    var com = scCommon.instance();
    var crEle = com.crEle;
    
    var dialog = null;
    var body = null;

    /**
     * 创建对话框视图
     * @param {*} button 对话框配置参数 
     * @param {*} listener 触发监听
     * @returns 
     */
    this.createView = function(button, listener){
        let clazz = "sc-dialog-box";

        if(button.childDialog){
            clazz = "sc-dialog-box-child";
        }else{
            //创建对话框，如果存在子对话框，则关闭
            childDialog = document.querySelector(".sc-dialog-box-child");
            if(childDialog){
                childDialog.classList.remove("active");
            }
        }

        dialog = document.querySelector("." + clazz);

        let head = null;
        let foot = null;

        if(!dialog){
            dialog = crEle(null, clazz);
            document.body.appendChild(dialog);
            document.body.addEventListener("keydown",(e)=>{
                if(e.keyCode == 27 || e.key == "Escape"){
                    dialog.classList.remove("active");
                }
            });
        }else{
            head = dialog.querySelector(".sc-dialog-head");
            body = dialog.querySelector(".sc-dialog-body");
            foot = dialog.querySelector(".sc-dialog-foot");
        }

        if(!head && (!button.dialog || button.dialog.head !== false)){
            head = crEle(null, "sc-dialog-head");

            let titleBar = crEle(null, "sc-dialog-titlebar");
            titleBar.innerText = button.label;

            let controlBar = crEle(null, "sc-dialog-controlbar");
            let close = crEle(null, "sc-dialog-controlbar-button");
            close.innerText = "×";

            controlBar.appendChild(close);

            close.addEventListener("click", ()=>{
                dialog.classList.remove("active");
            });

            if(button.help){
                let help = crEle(null, "sc-dialog-controlbar-button");
                help.innerText = "？";

                controlBar.appendChild(help);

                help.addEventListener("click", ()=>{
                    alert("尚未发布");
                });
            }

            head.appendChild(titleBar);
            head.appendChild(controlBar);

            dialog.appendChild(head);
        }else if(head && button.dialog && button.dialog.head === false){
            head.parentNode.removeChild(head);
        }
        
        if(head && head.parentNode){
            let titlebar = head.querySelector(".sc-dialog-titlebar");
            if(titlebar){
                titlebar.innerText = button.label;
            }        
        }

        if(!body){
            body = crEle(null, "sc-dialog-body");
            dialog.appendChild(body);
        }

        if(!foot && (!button.dialog || button.dialog.foot !== false)){
            foot = crEle(null, "sc-dialog-foot");

            let closeBtn = crEle("button", "sc-dialog-button,sc-button-close");
            closeBtn.innerText = "关闭";

            closeBtn.addEventListener("click", ()=>{
                dialog.classList.remove("active");
                delete this.beforeSubmit;
            });

            foot.appendChild(closeBtn);

            dialog.appendChild(foot);
        }else if(foot && button.dialog && button.dialog.foot === false){
            foot.parentNode.removeChild(foot);
        }

        if(foot && foot.parentNode){
            var oldOkBtn = foot.querySelector(".sc-button-ok");

            if(oldOkBtn){
                oldOkBtn.parentNode.removeChild(oldOkBtn);
            }
        }

        body.innerHTML = "";

        if(button.component){
            if(foot){
                body.appendChild(button.component.createView({
                    listener: listener
                }));

                let okBtn = crEle("button", "sc-dialog-button,sc-button-ok");
                okBtn.innerText = "确定";
    
                okBtn.addEventListener("click", ()=>{
                    okBtn.disabled = true;
                    
                    let submit = (data, option)=>{
                        if(option && option.beforeSubmit){
                            data = option.beforeSubmit(data);
                            delete option.beforeSubmit;
                        }else if(this.beforeSubmit){
                            data = this.beforeSubmit(data);
                            delete this.beforeSubmit;
                        }

                        let command = button.command;
                        if(data.$command){
                            command = data.$command;
                            delete data.$command;
                        }
    
                        if(this.submit){
                            this.submit(data, option);
                            delete this.submit;
                        }else{
                            listener(command, data, option);
                        }
    
                        dialog.classList.remove("active");
                    };

                    try{
                        let data = button.component.getData();
                        if(data && data.constructor.name == "Promise"){
                            data.then((result)=>{
                                submit(result.$value != null ? result.$value : result, result.$option);
                            });
                        }else{
                            submit(data.$value != null ? data.$value : data, data.$option);
                        }
                    }catch(e){
                        showError(e);
                        okBtn.disabled = false;
                    }
                });
    
                foot.appendChild(okBtn);
            }else{
                body.appendChild(button.component.createView({
                    listener: listener,
                    triggerListener: (value, option)=>{
                        return listener(button.command, value, option);
                    }
                }));
            }
        }

        dialog.classList.add("active");

        resize(dialog);

        setTimeout(()=>{
            let inputs = body.querySelectorAll("input[type='text']");
            if(inputs.length > 0){
                inputs[0].focus();
            }
        }, 300);

        setMove(dialog, button);

        var observer = new ResizeObserver(()=>{
            resize(dialog);
        });

        observer.observe(dialog);
    
        return dialog;
    }

    /**
     * 显示错误
     * @param {*} error 
     */
    var showError = function(error){
        let node = body.querySelector(".sc-dialog-error");
        if(!node){
            node = crEle("div", "sc-dialog-error");
            body.appendChild(node);
        }
        node.innerText = error;
    }

    /**
     * 调整位置
     * @param {*} dialog 
     */
    var resize = function(dialog){
        var left = 0;
        var top = 0;

        if(layout.width){
            left = layout.left + (layout.width - dialog.clientWidth) / 2;
            top = layout.top + (layout.height - dialog.clientHeight) / 2;
        }else{
            left = layout.left + 10;
            top = layout.top + 5 - dialog.clientHeight / 2;
        }
        
        dialog.style.left = left + "px";
        dialog.style.top = top + "px";
    }

    /**
     * 当前移动的元素
     */
    var currentMoveElement = null;

    /**
     * 使得元素可以被鼠标移动
     * @param {*} element 
     * @param {*} button
     */
    var setMove = function(element, button){
        if(button.__canMove) return;
        
        var head = element.querySelector(".sc-dialog-head");
        if(!head) return;

        head.addEventListener("mousedown",(e)=>{
            element.__mousedown = true;
            element.__left = parseFloat(element.style.left);
            element.__top = parseFloat(element.style.top);
            element.__pageX = e.pageX;
            element.__pageY = e.pageY;

            currentMoveElement = element;
        });

        head.addEventListener("mousemove", (e)=>{
            if(element.__mousedown){
                element.style.left = (element.__left + (e.pageX - element.__pageX)) + "px";
                element.style.top = (element.__top + (e.pageY - element.__pageY)) + "px"
            }
        });

        head.addEventListener("mouseup", ()=>{
            element.__mousedown = false;
            currentMoveElement = null;
        });

        button.__canMove = true;
    }

    /**
     * 添加监听器
     */
    var addGlobalListener = function(){
        document.body.removeEventListener("mousemove", documentMousemove);
        document.body.addEventListener("mousemove", documentMousemove);

        document.body.removeEventListener("mouseup", documentMouseup);
        document.body.addEventListener("mouseup", documentMouseup);
    }

    /**
     * 文档鼠标移动事件
     */
    var documentMousemove = function(e){
        if(currentMoveElement){
            currentMoveElement.style.left = (currentMoveElement.__left + (e.pageX - currentMoveElement.__pageX)) + "px";
            currentMoveElement.style.top = (currentMoveElement.__top + (e.pageY - currentMoveElement.__pageY)) + "px"
        }
    }

    /**
     * 文档鼠标弹起事件
     */
    var documentMouseup = function(e){
        if(currentMoveElement){
            currentMoveElement.__mousedown = false;
            currentMoveElement = null;
        }
    }

    //添加全局监听
    addGlobalListener();

    /**
     * 布局大小
     */
    var layout = null;

    /**
     * 设置布局大小
     * @param {*} lay 
     */
    this.setLayout = function(lay){
        layout = lay;
    }
}